//
//  ExerciseDetailViewController.m
//  Founder_study
//
//  Created by hongbao.cui on 14-8-5.
//  Copyright (c) 2014年 com.founder. All rights reserved.
//

#import "ExerciseDetailViewController.h"
#import "FMSNetWorkModule.h"
#import "ZipArchive.h"
#import "SynExericisesPaperData.h"
#import "Sqlite.h"
#import "SwipeView.h"
#import "ApplicationUtils.h"
#import "FMNavgationItem.h"
@interface ExerciseDetailViewController ()

@end

@implementation ExerciseDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)initNetData{
    NSString *urlString = [self.urlDict objectForKey:@"exerciseFileURL"];
//    NSString *urlString = @"http://study.yuetong.cn:8080/drappub/rest/mobilestudy/paper/8056?authToken=feixiang0";
    //初始化Documents路径
    NSString *path = FMPAPERSAVE_PATH;//[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Paper"];
    //初始化保存ZIP文件路径
    if ([ApplicationUtils isFileExitsAtPath:path]) {
        FMSCHBLog(@"创建目录成功");
    }
    NSString *paperId = [NSString stringWithFormat:@"%@",[self.urlDict objectForKey:@"exerciseID"]];
    NSString *paperStr = [NSString stringWithFormat:@"paper_%@.zip",paperId];
    NSString *filePath = [path stringByAppendingPathComponent:paperStr];
    [ApplicationUtils promptRotateWithViewTitle:@"加载中..." showView:self.view];
//    BOOL   success = [Sqlite deleteTestQuestionIdAt:paperId];//当id一致时先清除数据
//    if (success) {
//        FMSCHBLog(@"试卷删除成功!");
//    }else{
//        FMSCHBLog(@"试卷删除失败!");
//    }
//    [[FMSNetWorkModule sharedInstance] downloadFatAssFileFrom:urlString toFile:filePath completionCB:^(id result) {
//        //初始化ZipArchive
//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
//                                                 0), ^{
//            ZipArchive *zip = [[ZipArchive alloc] init];
//            BOOL success = NO;
//            if ([zip UnzipOpenFile:filePath]) {
//                success = [zip UnzipFileTo:path overWrite:YES];//解压文件
//                [zip UnzipCloseFile];//关闭
//                if (!success) {
//                    //解压失败
//                }else {
//                    //解压成功
//                    FMSCHBLog(@"unzip success.............");
                    NSError *error = nil;
//                    NSString *pathStr = [NSString stringWithFormat:@"%@/paper.XML",path];
//                    NSString *paperXmlString = [NSString stringWithContentsOfFile:pathStr encoding:NSUTF8StringEncoding error:&error];
    NSString *pathStr = [[NSBundle mainBundle] pathForResource:@"Paper" ofType:@"xml"];
    NSString *paperXmlString = [NSString stringWithContentsOfFile:pathStr encoding:NSUTF8StringEncoding error:&error];
                    if (!error) {
                        SynExericisesPaperData *paperData = [[SynExericisesPaperData alloc] init];
                        NSMutableDictionary *paperDict = [paperData PaperData:paperXmlString];
                        FMSCHBLog(@"paperDict:%@",paperDict);
//                        if (!self.dataQuestionDict) {
//                            self.dataQuestionDict = [NSMutableDictionary dictionaryWithDictionary:paperDict];
//                        }
                        NSString *paper_title_ = [paperDict objectForKey:@"paper_title"];
                        NSString *paper_score_ = [paperDict objectForKey:@"paper_score"];
                        NSString *paper_time_ = [paperDict objectForKey:@"paper_time"];
                        NSMutableArray *array = [paperDict objectForKey:@"questions"];
                        NSMutableArray *questions = [NSMutableArray arrayWithCapacity:1];
                        //                NSMutableArray *array_ = [Sqlite selectTestQuestion:paperId];
                        if (!self.paperArray) {
                            self.paperArray = [NSMutableArray array];
                        }
                        NSInteger number = 0;
                        for (int i=0; i<[array count]; i++) {
                            NSMutableArray *questionArray = [[array objectAtIndex:i] objectForKey:@"question"];
                            NSString *qtype_name =  [[array objectAtIndex:i] objectForKey:@"type_name"];
                            [self.paperArray removeAllObjects];
                            [self.paperArray addObjectsFromArray:questionArray];
                            NSMutableString *answerStr_ = [[NSMutableString alloc] initWithCapacity:1];
                            for (int j=0; j<[self.paperArray count]; j++) {
                                NSMutableDictionary *dataDict = [self.paperArray objectAtIndex:j];
                                NSString *qtype = [dataDict objectForKey:@"qtype"];
                                if ([qtype isEqualToString:@"1"]||[qtype isEqualToString:@"2"]) {
                                    [questions addObjectsFromArray:questionArray];
                                    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:paperId,@"paper_id",[dataDict objectForKey:@"questionContent"],@"content",@"1",@"user_error_count",@"0",@"user_right_count",@"0",@"favourite_flag",@"0",@"user_test_sign",[dataDict objectForKey:@"orderid"],@"qst_no",@"",@"user_answer",nil];
                                    [dataDict addEntriesFromDictionary:dict];
                                    
                                    NSString *has_sub = [dataDict objectForKey:@"has_sub"];
                                    FMSCHBLog(@"cui---hong-------has_sub-----------%@",has_sub);
                                    if (!has_sub) {
                                        has_sub = @"";
                                    }
                                    [dataDict setObject:has_sub forKey:@"has_sub"];
                                    [dataDict setObject:paper_title_ forKey:@"paper_title"];
                                    [dataDict setObject:paper_score_ forKey:@"paper_score"];
                                    [dataDict setObject:paper_time_ forKey:@"paper_time"];
                                    [dataDict setObject:qtype_name forKey:@"qtype_name"];
                                    [dataDict setObject:[NSString stringWithFormat:@"%ld",(long)number] forKey:@"qst_no"];
                                    BOOL success = [Sqlite insertTestQuestion:dataDict];
                                    if (success) {
                                        FMSCHBLog(@"====cuihongbao===%d==>存储成功！",j);
                                    }else{
                                        FMSCHBLog(@"====cuihongbao=====>存储失败！");
                                    }
                                    number++;
                                }else if([qtype isEqualToString:@"3"]){
                                    //判断题
                                    [questions addObjectsFromArray:questionArray];
                                    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:paperId,@"paper_id",[dataDict objectForKey:@"questionContent"],@"content",@"1",@"user_error_count",@"0",@"user_right_count",@"0",@"favourite_flag",@"0",@"user_test_sign",[dataDict objectForKey:@"orderid"],@"qst_no",@"",@"user_answer",nil];
                                    [dataDict addEntriesFromDictionary:dict];
                                    
                                    NSArray  *array = [NSArray arrayWithObjects:@"正确",@"错误",nil];
                                    NSMutableDictionary *optionsDict = [NSMutableDictionary dictionaryWithCapacity:1];
                                    [optionsDict setObject:array forKey:@"options"];
                                    NSString *has_sub = [dataDict objectForKey:@"has_sub"];
                                    FMSCHBLog(@"cui---hong-------has_sub-----------%@",has_sub);
                                    if (!has_sub) {
                                        has_sub = @"";
                                    }
                                    [dataDict setObject:has_sub forKey:@"has_sub"];
                                    [dataDict addEntriesFromDictionary:optionsDict];
                                    [dataDict setObject:paper_title_ forKey:@"paper_title"];
                                    [dataDict setObject:paper_score_ forKey:@"paper_score"];
                                    [dataDict setObject:paper_time_ forKey:@"paper_time"];
                                    [dataDict setObject:qtype_name forKey:@"qtype_name"];
                                    [dataDict setObject:[NSString stringWithFormat:@"%ld",(long)number] forKey:@"qst_no"];
                                    BOOL success = [Sqlite insertTestQuestion:dataDict];
                                    if (success) {
                                        FMSCHBLog(@"====cuihongbao===%d==>存储成功！",j);
                                    }else{
                                        FMSCHBLog(@"====cuihongbao=====>存储失败！");
                                    }
                                    number++;
                                }else{//简答题,案例分析题
                                    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithCapacity:1];
                                    [answerStr_ appendFormat:@"<p>%@</p>",[dataDict objectForKey:@"answer"]];
                                    [dict addEntriesFromDictionary:[NSDictionary dictionaryWithObject:answerStr_ forKey:@"answer"]];
                                    [dict addEntriesFromDictionary:[NSDictionary dictionaryWithObject:[dataDict objectForKey:@"questionContent"] forKey:@"content"]];
                                    [dict setObject:paperId forKey:@"paper_id"];
                                    [dict addEntriesFromDictionary:dataDict];
                                    [dict setObject:paper_title_ forKey:@"paper_title"];
                                    [dict setObject:paper_score_ forKey:@"paper_score"];
                                    [dict setObject:paper_time_ forKey:@"paper_time"];
                                    [dict setObject:qtype_name forKey:@"qtype_name"];
                                    [dict setObject:[NSString stringWithFormat:@"%ld",(long)number] forKey:@"qst_no"];
                                    BOOL success = [Sqlite insertTestQuestion:dict];
                                    if (success) {
                                        FMSCHBLog(@"====cuihongbao===%d==>存储成功！",j);
                                    }else{
                                        FMSCHBLog(@"====cuihongbao=====>存储失败！");
                                    }
                                    [dict removeAllObjects];
                                    number++;
                                }
                            }
                            
                        }
                        NSMutableArray *array_afterSave = [Sqlite selectTestQuestion:paperId];
                        [self.paperArray removeAllObjects];
                        [self.paperArray addObjectsFromArray:array_afterSave];
                        NSString *paper_title = nil;
                        if ([self.paperArray count]>0) {
                            paper_title = [[self.paperArray objectAtIndex:0] objectForKey:@"paper_title"];
                        }else{
                            [ApplicationUtils promptRemove];
                            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"试卷加载失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                            [alert setTag:4];
                            [alert show];
                            return ;
                        }
                        NSString *paperTitleAndCount = [NSString stringWithFormat:@"%@ 共%d/%lu题",paper_title,1,(unsigned long)[self.paperArray count]];
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self initExerciseView:paperTitleAndCount];
                        });
                        
                    }
//                }
//            }else{
//                FMSCHBLog(@"open fail................");
//            }
//        });
//
//    }];

}
-(void)initExerciseView:(NSString *)paperTitleAndCount{
    CGSize size = [paperTitleAndCount sizeWithFont:[UIFont systemFontOfSize:13.0] constrainedToSize:CGSizeMake(235, 70) lineBreakMode:NSLineBreakByWordWrapping];
    [titleLabel setText:paperTitleAndCount];
    [titleLabel setTextColor:[UIColor whiteColor]];
    [titleLabel setFrame:CGRectMake(10, (MAX(titleLabel.frame.size.height, 30)-size.height)/2, size.width, size.height)];
    [headerBg setFrame:CGRectMake(0, 0, FMSCREENWIDTH, MAX(titleLabel.frame.size.height, 30))];
    
    NSDictionary *dataDict = [self.paperArray objectAtIndex:0];//更新第一题收藏按钮
    //更新收藏按钮
    NSString *favourite_flag = [NSString stringWithFormat:@"%@",[dataDict objectForKey:@"favourite_flag"]];
    BOOL isCollection = NO;
    if ([favourite_flag isEqualToString:@"1"]) {
        isCollection = YES;
    }
    [collectionBtn setSelected:isCollection];
    
    [self.swipeView reloadData];
    [ApplicationUtils promptRemove];
}
-(void)back{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
-(void)initItem{
    FMNavgationItem* leftItem = [[FMNavgationItem alloc] init];
    [leftItem.backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItems = [leftItem getNavgationItemWithType:WRNavgationTypeLeft Ima:[ApplicationUtils getLocalImage:@"Navigation-Bar_Return_btn_@2x"] ImaHighlight:[ApplicationUtils getLocalImage:@"Navigation-Bar_Return_btn_@2x"] title:@""];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initItem];
    // Do any additional setup after loading the view.
    FMSCHBLog(@"------urlDict---%@",self.urlDict);
    self.navigationItem.title = @"同步练习";
    NSString *paperId = [NSString stringWithFormat:@"%@",[self.urlDict objectForKey:@"exerciseID"]];
    NSMutableArray *array_afterSave = [Sqlite selectTestQuestion:paperId];
    if (!self.paperArray) {
        self.paperArray = [NSMutableArray arrayWithCapacity:1.0];
    }
    [self.paperArray removeAllObjects];
    [self.paperArray addObjectsFromArray:array_afterSave];
    if ([self.paperArray count]>0) {
       NSString *paper_title = [[self.paperArray objectAtIndex:0] objectForKey:@"paper_title"];
        NSString *paperTitleAndCount = [NSString stringWithFormat:@"%@ 共%02i/%d题",paper_title,01,[self.paperArray count]];
        [self initExerciseView:paperTitleAndCount];
    }else{
        [self initNetData];
    }
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
@end
